<template>
  <el-card class="member-gallery-card">
    <h2 class="section-title mb-4">家族名人</h2>
    <div 
      class="member-grid" 
      @dragover.prevent
      @drop="handleDrop"
    >
      <div 
        v-for="(member, index) in clanMembers" 
        :key="index" 
        class="member-item"
        draggable="true"
        @dragstart="handleDragStart($event, index)"
      >
        <MemberCard :member="member" />
      </div>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import MemberCard from './MemberCard.vue';

const clanMembers = ref([
  { name: '黄生', avatar: 'ouyangxiu.jpg', title: '605lab' },
  { name: '黄生', avatar: 'ouyangxiu.jpg', title: '605lab' },
  { name: '黄生', avatar: 'ouyangxiu.jpg', title: '605lab' },
  { name: '黄生', avatar: 'ouyangxiu.jpg', title: '605lab' },
  { name: '黄生', avatar: 'ouyangxiu.jpg', title: '605lab' },
  { name: '黄生', avatar: 'ouyangxiu.jpg', title: '605lab' },
  { name: '黄生', avatar: 'ouyangxiu.jpg', title: '605lab' },
  { name: '黄生', avatar: 'ouyangxiu.jpg', title: '605lab' },
  { name: '黄生', avatar: 'ouyangxiu.jpg', title: '605lab' },
  { name: '黄生', avatar: 'ouyangxiu.jpg', title: '605lab' },
  { name: '黄生', avatar: 'ouyangxiu.jpg', title: '605lab' },
  { name: '黄生', avatar: 'ouyangxiu.jpg', title: '605lab' },
]);

const handleDragStart = (event: DragEvent, index: number) => {
  event.dataTransfer?.setData('text/plain', index.toString());
};

const handleDrop = (event: DragEvent) => {
  const draggedIndex = parseInt(event.dataTransfer?.getData('text/plain') || '');
  
  // 安全检查：确保event.target存在且是HTMLElement类型，并且有parentNode
  if (!event.target || !(event.target instanceof HTMLElement) || !event.target.parentNode) {
    return;
  }
  
  const parentNode = event.target.parentNode as HTMLElement;
  const targetElement = event.target as HTMLElement;
  const targetIndex = Array.from(parentNode.children).indexOf(targetElement);
  
  if (draggedIndex !== targetIndex && draggedIndex >= 0 && targetIndex >= 0) {
    [clanMembers.value[draggedIndex], clanMembers.value[targetIndex]] = [
      clanMembers.value[targetIndex], clanMembers.value[draggedIndex]
    ];
  }
};
</script>

<style lang="scss" scoped>
.member-gallery-card {
  background: linear-gradient(135deg, #f0f8f5 0%, #e8f5f0 100%);
  border: 1px solid #b3d9c9;
  padding: 1.2rem;
}

.member-grid {
  display: flex;
  gap: 1.5rem;
  overflow-x: auto; /* 添加水平滚动 */
  min-width: 600px; /* 根据卡片数量调整 */
  
  .member-item {
    transition: transform 0.2s ease;
    
    &:hover {
      cursor: grab;
    }
    
    &.dragging {
      opacity: 0.7;
    }
  }
}
</style>